<template>
  <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto" class="box">
       <h4>注册</h4>
    <el-form-item label="用户名" prop="username">
      <el-input v-model="ruleForm.username" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="ruleForm.password" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        去注册
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">去登录</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import router from '@/router'
import { ElMessage } from 'element-plus'
import requier from '@/requier/requier'
import { reactive, ref } from 'vue'
const ruleFormRef = ref()
const ruleForm = reactive({
  username: '',
  password: '',
})
// 邮箱的
const rules = reactive({
  username: [
    { pattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/, message: '请输入用户名', trigger: 'blur' },
  ],
  password: [
    { pattern: /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{6,16$}/, message: '请输入密码', trigger: 'blur' }
  ],
})
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      requier.post('/register', ruleForm).then(res => {
        console.log(res);
        if (res.data.code == 10000) {
          ElMessage({
            message: '注册成功',
            type: 'success',
          })
          router.push('/login')
        } else {
          ElMessage.error('注册失败')
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
</script>

<style lang="scss" scoped>
.box {
  width: 100%;
  height: 100%;
  border: 1px solid #000;
}
</style>